<?php
/**[栏目模型]
 * @Author: 976123967@qq.com
 * @Date:   2014-08-15 14:31:39
 * @Last Modified by:   Administrator
 * @Last Modified time: 2014-12-01 09:48:30
 */
class CategoryModel extends Model{

	protected $tableName='category';
	public $category;

    public function _initialize()
    {
    	
        $this->category = S('category');
    }


	// 自动验证
	/* array(验证字段,验证规则,错误提示,[验证条件,附加规则,验证时间])
	*
	*  验证条件
	*  Model::EXISTS_VALIDATE 或者0 存在字段就验证 （默认）
	*  Model::MUST_VALIDATE 或者1 必须验证
	*  Model::VALUE_VALIDATE或者2 值不为空的时候验证
	*
	*  验证时间
	*  Model:: MODEL_INSERT 或者1新增数据时候验证
	*  Model:: MODEL_UPDATE 或者2编辑数据时候验证
	*  Model:: MODEL_BOTH 或者3 全部情况下验证（默认）
	* */

	protected $_validate = array(
	   	array('cname','require','分类名不能为空',1),
	   	array('pid','check_pid','不能选择自己',1,'callback',2),
	   	array('default_tpl','require','封面模板不能为空',1),
	   	array('list_tpl','require','列表页模板不能为空',1),
	   	array('view_tpl','require','详细页模板不能为空',1),
	   	array('remark','require','请输入控制器名称',1),
	);

	// 自动完成
	/* array(填充字段,填充内容,[填充条件,附加规则])
	*  填充条件
	*  Model:: MODEL_INSERT或者1 新增数据的时候处理（默认）
	*  Model:: MODEL_UPDATE或者2更新数据的时候处理
	*  Model:: MODEL_BOTH或者3所有情况都进行处理
	* 
	**/
	protected $_auto = array(
		array('remark','_ucfirst',3,'callback'),
		array('sort','intval',3,'function') 
	);
	/**
	 * [_ucfirst 处理控制器名称]
	 * @param  [type] $con [description]
	 * @return [type]      [description]
	 */
	protected function _ucfirst($con)
	{
		// 全部转成小写，在首字母大写
		return ucfirst(strtolower($con));
	}


	/**
	 * [check_pid 验证父级pid]
	 * @return [type]      [description]
	 */
	public function check_pid()
	{
		// 父级pid
		$pid =I('post.pid',null,'intval');
		// cid
		$cid = I('post.cid',null,'intval');
 		// 编辑时候判断父级和cid 不能相同
		if($cid == $pid)
		{
			return false;
		}
		return true;
	}



    //获得数状子栏目 树状
	public function get_child_list($cid)
	{
		$category=$this->category;
		return  Data::channelList($category,$cid,'&nbsp;&nbsp;&nbsp;&nbsp;');
	}

	/**
	 * [get_parent_child 获取栏目子集 树状]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function get_parent_child($cid)
	{
		$pids = $this->get_parent_cid($cid);
		$pids = array_reverse($pids);
		$category = $this->category;
		return Data::channelList($category,$pids[0],'---');
	}


	/**
	 * [get_child_cid 子栏目的所有的cid]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function get_child_cid($cid)
	{
		$data =$this->get_child_list($cid);
		$result = array($cid);
		foreach($data as $v)
		{
			$result[]= $v['cid'];
		}
		return $result;
	}



	// 栏目父级
	public function get_parent_cate($cid)
	{
		$category=$this->category;
		return Data::parentChannel($category,$cid);
	}

	// 栏目父级cid
	public function get_parent_cid($cid)
	{
		$data =$this->get_parent_cate($cid);
		$result  = array();
		foreach($data as $v)
		{
			$result[] =$v['cid'];
		}
		return $result;
	}


	//获得数状栏目 树状
	public function get_tree_data()
	{
		$category=$this->category;
		return  Data::tree($category,'cname','cid');
	}



	/**
	 * [add_category 添加分类]
	 */
	public function add_category()
	{

		$data=$this->data;
		// 上传图片
		if(!$pic=$this->alter_pic())
			return false;
		elseif($pic!=1)
		{
			$data['pic']=$pic;
		}

		// 执行模型的add方法
		$this->add($data);
	}

	/**
	 * [alter_pic 上传图片]
	 * @return [type] [description]
	 */
	public function alter_pic()
	{

		$cid = I('post.cid');
		if($cid&&!empty($_FILES['pic']['name']))
		{
			$pic = $this->get_field($cid,'pic');
			is_file($pic) && unlink($pic);
		}

		if(!empty($_FILES['pic']['name']))
		{
			// 上传类
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 314572800 ;// 设置附件上传大小
            $upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg','pdf','apk','rar','zip');// 设置附件上传类型
            $savePath = './Data/Uploads/image/'.date('Y').'/'.date('m').'/'.date('d').'/';
            // 创建目录
            is_dir($savePath) || mkdir($savePath,0777,true);
            // 执行上传
            if($info=$upload->uploadOne($_FILES['pic'],$savePath))
                return $info[0]['savepath'].$info[0]['savename'];
            else
            {
            	$this->error=$upload->getErrorMsg();
            	return false;
            }

		}
		else
			return 1;
	}


	/**
	 * [find_one 获取单条信息]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function  find_one($cid)
	{
		// 读取缓存中的数据
		foreach($this->category as $v)
		{
			if($v['cid']==$cid)
			{
				return $v;
			}
		}


		// 执行模型中的find
		// return $this->find($cid);
	}


	/**
	 * [save_category 更新分类]
	 * @return [type] [description]
	 */
	public function save_category()
	{

		$data=$this->data;
		// 上传图片
		if(!$pic=$this->alter_pic())
			return false;
		elseif($pic!=1)
		{
			$data['pic']=$pic;
		}
		//执行模型save方法
		$this->save($data);
	}


	/**
	 * [delete_category 删除分类信息]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function delete_category($cid)
	{
		// 是否有子分类
		if($this->where("pid=$cid")->count())
		{
			$this->error='请先删除子分类';
			return false;
		}

		// 单页面
		$catType = $this->get_field($cid,'cat_type');
		if($catType==4)
		{
			$articleModel = D('Article');
			$aid = $articleModel->get_article_cid($cid);
			$articleModel->del_article($aid);
		}

		// 判断是否有商品属于这个分类
		if(M('article')->where(array('category_cid'=>$cid))->count())
		{
			$this->error='该分类下还有文章';
			return false;
		}
		// 删除图
		$pic = $this->get_field($cid,'pic');
		is_file($pic) && unlink($pic);
		$this->delete($cid);
		return true;
	}

	/**
	 * [update_order 排序]
	 * @return [type] [description]
	 */
	public function update_order()
	{
		$cid = I('post.cid');
		if(empty($cid))
		{
			$this->error='没有栏目用于排序';
			return false;
		}
		$listOrder = I('post.list_order');
		foreach($cid as $k => $v)
		{
			$data = array(
				'sort'=>$listOrder[$k]
			);
			$this->where(array('cid'=>$v))->save($data);
		}
		return true;
	}

	/**
	 * [get_parent_category 获取所有的父级]
	 * @param  [type] $cityid [description]
	 * @return [type]         [description]
	 */
	public function get_parent_category($cid)
	{
		return  Data::parentChannel($this->category,$cid,'cid');
	}
	/**
	 * [get_parent_category_cid 获取所有的父级cid]
	 * @param  [type] $cityid [description]
	 * @return [type]         [description]
	 */
	public function get_parent_category_cid($cid)
	{
		$data =  Data::parentChannel($this->category,$cid,'cid');
		$result = array();
		if(!$data) return false;
		foreach($data as $v)
		{
			$result[]=$v['cid'];
		}
		return $result;
	}



	//更新栏目缓存
	public function update_cache()
	{
		$category=$this->order(array('sort'=>'asc'))->select();
		$data=array();
		if(!empty($category))
		{
			$modelModel = D('Model');
			foreach($category as $n=>$v)
			{
				$v['disabled']='';
				if($v['cat_type']==1)
				{
					$v['type']="普通";
				}
				elseif($v['cat_type']==2)
				{
					$v['disabled']='disabled="disabled"';
					$v['type']="封面";
				}
				elseif($v['cat_type']==3)
				{
					
					$v['type']="跳转";
				}
				elseif($v['cat_type']==4)
				{
					$v['type']="单页";
				}

				$v['showtarget']='';
				if($v['target'] == 2)
				{
					$v['showtarget']='target="_blank"';
				}
				if($v['pic'])
				{
					$v['has_pic'] = true;
				}

				$v['pic']= $v['pic']?__ROOT__.'/'.$v['pic']:__ROOT__.'/Data/Image/default.gif';
				
				$v['model'] = $modelModel->get_field($v['model_mid'],'remark');
				$data[]=$v;
			}
		}
		S('category',$data);
	}

	/**
	 * [get_field 获取字段信息]
	 * @param  [type] $cid   [description]
	 * @param  string $field [description]
	 * @return [type]        [description]
	 */
	public function get_field($cid,$field='cname')
	{
		return $this->where(array('cid'=>$cid))->getField($field);
	}



	/**
	 * [get_nav 获取导航]
	 * @param  [type] $pid [description]
	 * @return [type]      [description]
	 */
	public function get_nav($pid=0)
	{
		$nav = array();
		// 没有栏目
		if(!$this->category) 
			return $nav;

		// 当前浏览的cid的所有父级cid
		$parentCids = array();
		if($cid = I('get.cid',null,'intval'))
			$parentCids = $this->get_parent_category_cid($cid);
		// 遍历栏目组合数组
		
		foreach($this->category as $k=> $v)
		{
			$nav[$k] = $v;
			$url = $this->get_url($v);
			$nav[$k]['url']= $url;
			// 判断高亮
			if(in_array($v['cid'], $parentCids))
				$nav[$k]['cur'] = 1;
			else
				$nav[$k]['cur'] = 0;
		
		}
		
		return  Data::channelLevel($nav,$pid);
	}

	/**
	 * [get_bread 获取面包屑导航]
	 * @return [type] [description]
	 */
	public function get_bread($cid)
	{
		// 所有父级
		$parent = $this->get_parent_category($cid);
		$parent = array_reverse($parent);
		$bread ="<a href='".__ROOT__."/'>首页</a> &gt; ";
		//$breadEn ="<a href='".__ROOT__."/'>Home</a> &gt; ";
		foreach ($parent as $k=> $v) 
		{
			
			$url = $this->get_url($v);
			if($k<count($parent)-1)
			{
				$bread .= "<a href='".$url."'>".$v['cname'].'</a> &gt; ';
				//$breadEn .= "<a href='".$url."'>".$v['cname_en'].'</a> &gt; ';
			}
			else
			{
				$bread.="".$v['cname']."";
				//$breadEn.="".$v['cname_en']."";
			}
		}
		//return array('bread'=>$bread,'bread_en'=>$breadEn);
		return array('bread'=>$bread);
	}


	/**
	 * [get_url 获取栏目链接]
	 * @param  [type] $cat [description]
	 * @return [type]      [description]
	 */
	public function get_url($cat)
	{

		// 根据类型生成url
		$temp = array('cat_type'=>$cat['cat_type'],'cid'=>$cat['cid'],'go_url'=>$cat['go_url']);

		// 有设置跳转到子栏目 并且有子栏目
		if($cat['go_child']&& $child = $this->get_child_list($cat['cid']))
		{

			$temp['cat_type']= $child[0]['cat_type'];
			$temp['cid']= $child[0]['cid'];
			$temp['go_url']= $child[0]['go_url'];
		}

		switch ($temp['cat_type']) {
			case 1: //普通栏目
				//unset($temp['cat_type']);
				//$url =  U('Home/'.$cat['remark'].'/lists',$temp);
				$url =  U($cat['remark']."/l_".$temp['cid']);
				break;
			case 2: //封面栏目
				//unset($temp['cat_type']);
				//$url = U('Home/'.$cat['remark'].'/cover',$temp);
				$url =  U($cat['remark']."/c_".$temp['cid']);
				break;
			case 3: //跳转
				$url = $temp['go_url'];
				break;
			case 4:
				//unset($temp['cat_type']);
				//$url = U('Home/'.$cat['remark'].'/view',$temp);
				$url = U($cat['remark'].'/v_'.$temp['cid']);
				break;	
		}

		/*switch ($temp['cat_type']) {
			case 1: //普通栏目
				unset($temp['cat_type']);
				unset($temp['go_url']);
				$url =  U('Home/'.$cat['remark'].'/lists',$temp);
				break;
			case 2: //封面栏目
				unset($temp['cat_type']);
				$url = U('Home/'.$cat['remark'].'/cover',$temp);
				break;
			case 3: //跳转
				$url = $temp['go_url'];
				break;
			case 4:
				unset($temp['cat_type']);
				unset($temp['go_url']);
				$url = U('Home/'.$cat['remark'].'/view',$temp);
				break;	
		}*/
		return $url;
	}


	/**
	 * [get_title 页面标题]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function get_title($cid)
	{
		// 所有父级
		$parent = $this->get_parent_category($cid);

		$title = "";
		//$titleEn = "";
		foreach ($parent as $k=> $v) 
		{
			$title .= "{$v['cname']} > ";
			//$titleEn .= "{$v['cname_en']} > ";
		}
		$title .= C('cfg_name');
		//$titleEn .= C('cfg_name_en');
		//return array('title'=>$title,'title_en'=>$titleEn);
		return array('title'=>$title);
	}


	/**
	 * [del_attachment 删除上传的图片或者删除上传的文件]
	 * @param  [type] $cid   [description]
	 * @param  [type] $field [description]
	 * @return [type]        [description]
	 */
	public function del_attachment($cid,$field)
	{

		// 删除文件
		$attachement = $this->get_field($cid,$field);
		is_file($attachement) && unlink($attachement);

		// 更新数据库
		$this->save(array('cid'=>$cid,$field=>''));

		// 更新缓存
		$this->update_cache();
	}



	// 更新更新缓存
	public function _after_insert($data,$options)
	{
		$this->update_cache();
	}
	public function _after_update($data,$options)
	{
		$this->update_cache();
	}
	public function _after_delete($data,$options)
	{
		$this->update_cache();
	}

}